const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatChineseDate = function (dt) {
  let date = new Date(dt)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return year + '年' + month + '月' + day + '日'
}

/**
 * 中文日期转为英文日期
 * @param {String} dtStr 中文日期字符串
 */
const chineseDateStrToDateStr = function (dtStr) {
  dtStr = String(dtStr).replace("年", "-")
  dtStr = String(dtStr).replace('月', '-')
  dtStr = String(dtStr).replace('日', '')

  return dtStr;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 取得图片的基础路径
 */
const getImgPath = function () {
  const app = getApp();
  return app.globalData.imgPath;
}

/**
 * 取得是否参加计划前
 */
const getBeforePlanned = function () {
  const app = getApp();
  return app.globalData.beforePlanned;
}

/**
 * 取得当前进入的场景值
 */
const getuserEnterAppletMode = function () {
  const app = getApp();
  return app.globalData.userEnterAppletMode;
}

/**
 * 设置是否计划前
 * @param {Boolean} val 
 */
const setBeforePlanned = function (val,status) {

  //console.log('val,statusval,status',val,status);
  const app = getApp();
  app.globalData.beforePlanned = val;
  // 用户状态
  app.globalData.beforePlannedSatus = status;

}

/**
 * 取得Tabbar激活项的名称
 */
const getTabtarActive = function () {
  const app = getApp();
  return app.globalData.tabbarActive;
}

/**
 * 设置tabbar活动项名称
 */
const setTabbarActive = function (name) {
  const app = getApp();
  app.globalData.tabbarActive = name;
}

/**
 * 取得网络接口基础地址
 */
const getBaseUrl = function () {
  const app = getApp();
  return app.globalData.baseUrl;
}

/**
 * 取得用户信息
 */
const getUserInfo = function () {
  const app = getApp();
  return app.globalData.userInfo;
}

/**
 * 设置全局userInfo
 */
const setUserInfo = function (userInfo) {
  const app = getApp();
  app.globalData.userInfo = userInfo;
}

/**
 * 取得登录数据
 */
const getLoginData = function () {
  const app = getApp();
  return app.globalData.loginData;
}

/**
 * 设置登录数据
 * @param {Object} data 
 */
const setLoginData = function (data) {
  const app = getApp();
  app.globalData.loginData = data;
}

/**
 * 取得OpenId
 */
const getOpenId = function () {
  const app = getApp();
  if (!app.globalData.loginData || !app.globalData.loginData.openid) return null;
  return app.globalData.loginData.openid;
}

/**
 * 取得token
 */
const getToken = function () {
 // const app = getApp();
 // if (!app.globalData.loginData || !app.globalData.loginData.token) return null;
  return wx.getStorageSync('token');//app.globalData.loginData.token;
}

/**
 * 登录微信，设置全局code
 * @param {Object} params {success{Function}成功回调函数}
 */
const loginWx = function (params) {


  wx.login({
    success: (res) => {
     // console.log(res);
      let code = res.code;
     
      //设置全局变量
      setCode(code);

      //回调
      params.success(res)
    },
  })


}

/**
 * 取得微信code
 */
const getCode = function () {
  const app = getApp();
  return app.globalData.code;
}

/**
 * 设置微信code
 * @param {String} code 
 */
const setCode = function (code) {
  const app = getApp();
  app.globalData.code = code;
}

/**
 * 设置微信客户 是否
 * @param {String} iskefu 
 */
const setiskefu = function (iskefu) {
  const app = getApp();
  app.globalData.iskefu = iskefu;
}

/**
 * 设置微信客户 是否
 * @param {String} iskefu 
 */
const getiskefu = function () {
  const app = getApp();
  return app.globalData.iskefu;
}

/**
 * 取得channel
 */
const getChannel = function () {
  const app = getApp()
  return app.globalData.channel;
}

/**
 * 取得share
 */
const getshare = function () {
  const app = getApp()
  return app.globalData.is_share;
}

/**
 * 设置channel
 * @param {String} channel 
 */
const setChannel = function (channel) {
  const app = getApp();
  app.globalData.channe = channel;
}

/**
 * 取得hash
 */
const getHash = function () {
  const app = getApp();
  return app.globalData.hash;
}

/**
 * 设置hash
 * @param {String} hash 
 */
const setHash = function (hash) {
  app.globalData.hash = hash;
}

/**
 * 登录服务器
 */
const loginServer = function () {
  //console.log("loginServer")
  //登录微信，并设置全局code
  loginWx({
    success(res) {
      //向本地服务器登录
   //   console.log("util.loginServer")
      let url = getBaseUrl() + "/api/user/loginByWechatCode";
      let data = {
        code: getCode(),
        channel: getChannel(),
        hash: getHash(),
        nickname: getUserInfo().nickName,
        head_image: getUserInfo().avatarUrl,
      }
     // console.log("loginServer,data", data)
      wx.request({
        url: url,
        method: 'POST',
        data: data,
        success(res) {
         // console.log("loginServer,res", res)
           if(res.data.code == 0){
               setLoginData(res.data.data)
           }
         
          // console.log("getLoginData", getLoginData())
        }
      })
    }
  })

}

/**
 * 封装微信请求
 * @param {Object} params 传入的参数对象
 */
const request = function (params) {
  wx.request({
    url: params.url,
    method: params.method ? params.method : "GET",
    data: params.data ? params.data : null,
    success(res) {
      // console.log("res", res)
      let data = res.data; 
      if (data.code == 10004) {
        let that = this;
        let pages = getCurrentPages(); // 获取页面指针数组
        let currentPage ; // 获取当前页
        currentPage = pages[pages.length - 1];
        let querys = queryParams(currentPage.options);   //获取参数
 
        // console.log('pages',pages);
        // console.log('currentPage',currentPage);
        // console.log('wewewess',querys);
        // console.log('currentPage.route',currentPage.route);
        // console.log();

        // wx.showToast({
        //   title: '6666',
        //   icon:'none',
        // })
        // wx.getSystemInfo({
        //   success:function(res){
        //     if(res.platform=="ios"){
        //       currentPage = pages[pages.length - 1];
        //     }else{
        //       currentPage = pages[pages.length];
        //     }
        //   }
        // });
      
        //pages/plan/joinPlan
        if(currentPage.route !='pages/projects/projects'){
          wx.showToast({
            title: data.msg,
            icon:'none',
          })
         // this.setTabbarActive('service');
          wx.setStorageSync('token', '')
          wx.clearStorageSync();       // 这里判断 如果当前页面是 pages/plan/joinPlan 就 跳去
         // let url = '/pages/index/index?query=nologin'+ '&currentPage=' + '/'+currentPage.route + '?' + querys
         const app = getApp();
         let url;
          // if(currentPage.route =='pages/plan/joinPlan'){
          //       url = '/pages/index/index?query=fengxiang';
          //       app.globalData.tabbarActive = 'plan';
         // }else{
            url = '/pages/index/index';
            app.globalData.tabbarActive = 'service';
        //  }

        //  if(currentPage.options.hasOwnProperty('query')){

        //   if(currentPage.options.query == '"fengxiang"'){
        //         url = '/pages/index/index?'+ querys;
        //   }

        //  }

          wx.redirectTo({
            url: url,
          })
          return;
        }
        //loginServer();
      }
      if (params.success)
        params.success(res);
    },
    fail(res) {
      if (params.fail) params.fail(res);
    },
    complete(res) {
      if (params.complete) params.complete(res);
    }
  })
}

function queryParams (data, isPrefix = false) {
  let prefix = isPrefix ? '?' : ''
  let _result = []
  for (let key in data) {
    let value = data[key]
    if (['', undefined, null].includes(value)) {
      continue
    }
    if (value.constructor === Array) {
      value.forEach(_value => {
        _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
      })
    } else {
      _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
}


/**
 * 取得图片的实际路径
 * @param {String} path 图片路径，不包括基础网络路径
 */
const getImageRealPath = function (path) {
  if (path.startsWith("http")) return path;
  if (path.startsWith("/"))
    return getImgPath() + path;
  else return getImgPath() + "/" + path;
}

/**
 * 取得IM SDKAPPID
 */
const getImSDKAPPID=function(){
  const app = getApp();
  return app.globalData.im_SDKAPPID;
}

/**
 * 取得七牛URL地址
 */
const getQiNiuUrl=function(){
  const app = getApp();
  return app.globalData.qiNiuUrl;
}

/**
 * 取得七牛bucket
 */
const getQiNuiBucket=function(){
  const app = getApp();
  return app.globalData.qiNuiBucket;
}




// 倒计时
const countDown = function (that) {  //倒计时函数
  let newTime = new Date().getTime();
  let endTime = that.data.endTime;
  let remainTime = endTime - newTime;
  let obj = null;
  let t = '';
  // 如果活动未结束，对时间进行处理
  if (remainTime > 0) {
    let time = remainTime / 1000;
    // 获取天、时、分、秒

    let day = parseInt(time / (60 * 60 * 24));
    //let day = Math.floor(time / 86400);
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    obj = {
      day: formatNumber(day),
      hou: formatNumber(hou),
      min: formatNumber(min),
      sec: formatNumber(sec)
    }
  }
  t = setTimeout(function() {
    that.setData({
      countDownTxt: obj
    });
    countDown(that)
  }, 1000)
  if (remainTime <= 0) {
    clearTimeout(t);
  }
}

module.exports = {
  formatTime,
  getImgPath,
  setiskefu,
  getiskefu,
  getBeforePlanned,
  setBeforePlanned,
  getTabtarActive,
  setTabbarActive,
  getBaseUrl,
  formatChineseDate,
  chineseDateStrToDateStr,
  getUserInfo,
  setUserInfo,
  getLoginData,
  setLoginData,
  getOpenId,
  getToken,
  request,
  getCode,
  setCode,
  getChannel,
  getshare,
  setChannel,
  getHash,
  setHash,
  loginWx,
  getImageRealPath,
  getImSDKAPPID,
  getQiNiuUrl,
  getQiNuiBucket,
  formatNumber,
  countDown,
  getuserEnterAppletMode
}